import {getUserTempId} from '@/utils/userabout'
import {reqRegisterCode,reqRegister,reqLogin,reqUserinfo,reqLogout} from '@/api'
const state = {
    // 存储这个唯一标识
    userTempId:getUserTempId(),
    code:'',//验证码
    // token:'',//登录成功的标识
    token:localStorage.getItem('userInfo_key'),//自动登录，从本地存储拿取数据
    userInfo:{}//用户信息
};
const mutations = {
    REQ_REGISTERCODE(state,code){
        state.code = code;
    },
    REQ_USERINFO(state,token){
        state.token = token;
    },
    REQ_GETUSERINFO(state,userInfo){
        state.userInfo = userInfo;
    },
    // 删除vuex里的token数据
    REQ_DELETETOKEN(state){
        state.token = '';
        // 删除用户信息
        state.userInfo = {};
    }
};
const actions = {
    // 去获取验证码
    async registerCode({commit},phone){
        const result = await reqRegisterCode(phone);
        if(result.code === 200){
            commit('REQ_REGISTERCODE',result.data)
            return result.data;
        }else{
            return Promise.reject(new Error('failed'));
        }
    },
    // 请求注册验证
    async register({commit},userInfo){
        const result = await reqRegister(userInfo);
        if(result.code === 200){
            return 'ok'
        }else{
            return Promise.reject(new Error('failed'))
        }
    },
    // 请求登录
    async userLogin({commit},userInfo){
        const result = await reqLogin(userInfo);
        if(result.code === 200){
            commit('REQ_USERINFO',result.data.token)//第一次登录拿到的token
            // 将拿到的token保存到localStorage
            localStorage.setItem('userInfo_key',result.data.token)
            return 'ok'
        }else{
            return Promise.reject(new Error('failed'))
        }
    },
    // 获取用户信息
    async getUserInfo({commit}){
        const result = await reqUserinfo();
        if(result.code === 200){
            commit('REQ_GETUSERINFO',result.data)
            return 'ok'
        }else{
            return Promise.reject(new Error('failed'))
        }
    },
    // 清空vux和localStorage里的数据
    // 修改数据不能直接修改state中的数据只能通过mutations来修改
    async deleteToken({commit}){
        // 删除vuex里的token和用户信息
        commit('REQ_DELETETOKEN');
        // 删除本地保存的token
        localStorage.removeItem('userInfo_key')
    },
    // 请求退出登录
    async logout({commit,dispatch}){
        const result = await reqLogout();
        if(result.code === 200){
            dispatch('deleteToken')
            return 'ok'
        }else{
            return Promise.reject(new Error('failed'))
        }
    }
};
const getters = {};

export default {
    state,
    actions,
    mutations,
    getters,
}